package com.excellent.mvvm.ext

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.blankj.utilcode.util.SizeUtils
import java.io.File
import java.text.DecimalFormat


fun Any.dpToPx(value: Int): Int {
    return SizeUtils.dp2px(value.toFloat())
}

@SuppressLint("DefaultLocale")
fun Long.toHHMMss(): String {
    val totalSeconds = this / 1000
    val hours = totalSeconds / 3600
    val remainingSeconds = totalSeconds % 3600
    val minutes = remainingSeconds / 60
    val seconds = remainingSeconds % 60
    return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}

fun Float.mbToGB(): String {
    return bytes2kb(this)
}

fun bytes2kb(bytes: Float): String {

    val df = DecimalFormat("#.0")
    var fileSizeString = ""
    val wrongSize = "0B"
    if (bytes == 0.0f) {
        return wrongSize
    }
    fileSizeString = if (bytes < 1024) {
        df.format(bytes.toDouble()) + "B"
    } else if (bytes < 1048576) {
        df.format(bytes.toDouble() / 1024) + "KB"
    } else if (bytes < 1073741824) {
        df.format(bytes.toDouble() / 1048576) + "MB"
    } else {
        df.format(bytes.toDouble() / 1073741824) + "GB"
    }
    return fileSizeString

}

fun getVideoThumbnail(videoPath: String): Bitmap? {
    val retriever = MediaMetadataRetriever()
    try {
        if (!File(videoPath).exists()) {
            return null
        }

        retriever.setDataSource(videoPath)
        return retriever.getFrameAtTime(1_000_000, MediaMetadataRetriever.OPTION_CLOSEST)
    } catch (e: Exception) {
        e.printStackTrace()
        return null
    } finally {
        retriever.release()
    }
}

//使用 Kotlin 的正则表达式来判断字符串 vimeo.com/1099020986 中斜杠 / 后面是否只包含数字
fun String.isVimeoUrlWithOnlyDigits(): Boolean {
//    val pattern =  Regex("^vimeo\\.com/(\\d+)$")
//    return pattern.matches(this)
    val pattern = "https://vimeo\\.com/\\d+\$".toRegex()
    return pattern.matches(this)
}

/**
 * 防止出现Can not perform this action after onSaveInstanceState
 */
fun DialogFragment.safeShow(fragmentManager: FragmentManager, tag: String) {
    if (!fragmentManager.isStateSaved) {
        this.show(fragmentManager, tag)
    } else {
        fragmentManager.beginTransaction()
            .add(this, tag)
            .commitAllowingStateLoss()
    }
}


/**
 * 防止延迟关闭的时候可能出现Can not perform this action after onSaveInstanceState
 */
fun DialogFragment.safeDismiss() {
    if (this.isAdded) {
        dismissAllowingStateLoss()
    }
}